package redisTest;

import com.it.Application;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * projectName: spring_boot_redis
 *
 * @author: 王宝贵
 * time: 2024/8/6 18:45 周二
 * description:
 */

@SpringBootTest(classes = Application.class)
public class redisTest001 {

    @Autowired
   private RedisTemplate redisTemplate;

    @Autowired
    private RedisScript<Boolean> script;

    /**
     * 字符串
     */
    @Test
    public void test1(){
        redisTemplate.opsForValue().set("name","王五");
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println(name);

        List list = new ArrayList<>();
        list.add("lucy");
        list.add("mary");
        redisTemplate.opsForValue().set("abc",list);
        System.out.println(redisTemplate.opsForValue().get("abc"));


    }

    /**
     * 集合
     */
    @Test
    public void test2(){
        redisTemplate.opsForList().leftPushAll("age","15",16);
        List age = redisTemplate.opsForList().range("age", 0, -1);
        System.out.println(age);

    }

    /**
     * 哈希
     */
    @Test
    public void test3(){
        // 存储哈希表
        String hashKey = "myHash";
        String field1 = "name";
        String value1 = "John";
        String field2 = "age";
        String value2 = "25";

        redisTemplate.opsForHash().put(hashKey, field1, value1);
        redisTemplate.opsForHash().put(hashKey, field2, value2);


        // 获取哈希表
        Object retrievedValue1 = redisTemplate.opsForHash().get(hashKey, field1);
        System.out.println("retrievedValue1 = " + retrievedValue1);
        Object retrievedValue2 = redisTemplate.opsForHash().get(hashKey, field2);
        System.out.println("retrievedValue2 = " + retrievedValue2);

    }

    @Test
    public void test() {

        //执行lua脚本
        /**
         * 修改密码！ 需要输入原密码！
         *    key -> password
         *    原 -> root
         *    新 -> admin
         *
         * 1.脚本对象
         * 2.keys的集合 [KEYS[从1开始]]
         * 3.ARGV的参数数组或者可变参数 从做到右 从1开始
         */
        List<String> keyList = Collections.singletonList("password");
        boolean flag = (boolean) redisTemplate.execute(script, keyList, "zhao6429598","xxxxx");

        System.out.println(flag?"密码修改成功！":"密码修改失败，原密码错误！");
    }

}